<?php
/**
 * Notes:
 * User: ysian
 * Time: 15:28
 * @return
 */

namespace Ysian\Alipaysdk\tools;

class Attachment
{
    public static function download($url,$filename='',$save_dir = './')
    {
        //检测文件是否存在
        self::isExist($url);

        if (trim($filename)=='') {
            $ext = strrchr($url,'.');
            $filename = Str::getRandomStr(10).$ext;
        }
        if (!file_exists($save_dir) && !mkdir($save_dir,0777,true)) {
            throw new \Exception('文件目录不存在');
        }
        if (strrpos($save_dir,'/')==0)  $save_dir .= '/';

        //获取文件资源
        $file = self::curl_get($url);

        $resource = fopen($save_dir . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        unset($file);
        return realpath(dirname('public')).'/'.$filename;
    }

    public static function isExist($url)
    {
        try {
            file_get_contents($url);
        } catch (\Exception $e){
            return $e->getMessage();
        }
    }

    public static function curl_get($url)
    {
        $ch = curl_init(); //创建一个新cURL资源

        //s设置选项,包括url
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        curl_close($ch);//释放curl句柄
        return $output;
    }
}